package com.qf.src;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProAndCum2 {
    public static void main(String[] args) {
        Products pp=new Products();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for(int i=0;i<10;i++){
                        pp.add();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for(int i=0;i<10;i++){
                        pp.del();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for(int i=0;i<10;i++){
                        pp.add();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for(int i=0;i<10;i++){
                        pp.del();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }




}

class Products{

    private int count=0;
    private Lock lock= new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();

    public void add() throws InterruptedException {
        lock.lock();

        while(count>0){
            condition1.await();
        }
        System.out.println("生产者执行了。。"+Thread.currentThread().getName()+"..start.."+ ++count);
        condition2.signalAll();
        lock.unlock();


    }
    public void del() throws InterruptedException {
        lock.lock();
        while(count<=0){
            condition2.await();
        }
        System.out.println("消费者执行了。。。"+Thread.currentThread().getName()+".. start.."+ --count);
        condition1.signalAll();
        lock.unlock();

    }
}
